package com.bwie.job;

import cn.hutool.core.bean.BeanUtil;
import com.bwie.es.EsOrder;
import com.bwie.mapper.TbOrderMapper;
import com.bwie.pojo.TbOrder;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author 军哥
 * @version 1.0
 * @description: TODO
 * @date 2025/5/7 14:06
 */

@Component
@Slf4j
public class SyncOrderJob implements Job {

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    TbOrderMapper tbOrderMapper;


    /**
     * @description 把订单同步到ES中
     * @params [jobExecutionContext]
     * @return void
     * @author 军哥
     * @date 2025/5/7 14:28
     */

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info("订单同步任务【开始】执行了~~~~~~~~~~~~~~~~~~~~~~~");

        //--1 检查索引，如果索引不存在，则创建索引
        IndexOperations indexOps = elasticsearchRestTemplate.indexOps(EsOrder.class);
        boolean exists = indexOps.exists();
        if(!exists) {
            log.info("索引不存在，创建索引");
            indexOps.create();

            // 创建映射
            Document mapping = indexOps.createMapping();
            indexOps.putMapping(mapping);
        }


        //--2 从MySQL数据库中读取订单数据
        List<TbOrder> orderAll = tbOrderMapper.getOrderAll();
        if(orderAll == null || orderAll.size() == 0) {
            log.error("没有任何订单数据，无需同步");
            return;
        }

        //--3 把订单数据存储到ES中
        for (TbOrder tbOrder : orderAll) {
            EsOrder esOrder = BeanUtil.toBean(tbOrder, EsOrder.class);

            elasticsearchRestTemplate.save(esOrder);
        }

        log.info("订单同步任务【结束】执行了~~~~~~~~~~~~~~~~~~~~~~~");
    }
}
